<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *产品库存申请记录
 */
class PartsStockReload extends Model
{
    use SoftDelete;

    protected $name = 'qingdongams_parts_stock_reload';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $hidden = ['deletetime', 'updatetime'];

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i', $value);
    }

    //创建人
    public function createStaff() {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
    }
    //获取详情
    public function getPartsAttr($value){
        return json_decode($value,true);
    }
    //添加库存记录
    public static function addRecord($params)
    {
        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
        }
        $flow = Flow::getsteplist(Flow::PARTS_STATUS);
        $params['flow_id'] = $flow['flow_id'];
        $params['order_id'] = $flow['order_id'];

        if ($flow['status'] == 0) {//发起人自选
            if (empty($params['flow_staff_ids'])) {
                throw new Exception('审批人必须选择');
            }
            $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
        } else {
            $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
        }

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->save($params);
        $lastId = $model->getLastInsID();
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($model->getError());
        }
        if ($flow['status'] == 1) {//固定审批
            //发送审批通知
            Flow::sendStepRecord($flow,Flow::PARTS_STATUS, $lastId);
        } else {//发起人自选 依次审批
            $staff_id   = explode(',', $params['flow_staff_ids'])[0];
            if ($staff_id) {
                ExamineRecord::addExaminse(ExamineRecord::PARTS_TYPE, $lastId, $staff_id);
            }
        }


        return $lastId;
    }
}
